package com.atguigu.day08;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ReducingState;
import org.apache.flink.api.common.state.ReducingStateDescriptor;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

public class Flink06_State_KeyedState_ReduceState {

    public static void main(String[] args) throws Exception {

        //1.获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        //2.读取数据
        DataStreamSource<String> socketTextStream = env.socketTextStream("hadoop102", 9999);

        //3.将每行数据转换为JavaBean
        SingleOutputStreamOperator<WaterSensor> waterSensorDS = socketTextStream.map(line -> {
            String[] fields = line.split(",");
            return new WaterSensor(fields[0],
                    Long.parseLong(fields[1]),
                    Double.parseDouble(fields[2]));

        });

        //4.按照传感器Id分组
        KeyedStream<WaterSensor, String> keyedStream = waterSensorDS.keyBy(WaterSensor::getId);

        //5.使用状态编程的方式实现累加水位线
        SingleOutputStreamOperator<Tuple2<String, Double>> result = keyedStream.process(new KeyedProcessFunction<String, WaterSensor, Tuple2<String, Double>>() {

            //定义状态
            private ReducingState<Double> reducingState;

            @Override
            public void open(Configuration parameters) throws Exception {
                reducingState = getRuntimeContext()
                        .getReducingState(new ReducingStateDescriptor<Double>("vc-state",
                                new ReduceFunction<Double>() {
                                    @Override
                                    public Double reduce(Double value1, Double value2) throws Exception {
                                        return value1 + value2;
                                    }
                                }, Double.class));
            }

            @Override
            public void processElement(WaterSensor value, Context ctx, Collector<Tuple2<String, Double>> out) throws Exception {

                //将当前数据累加至状态中
                reducingState.add(value.getVc());

                //输出数据
                out.collect(new Tuple2<>(value.getId(), reducingState.get()));
            }
        });

        //6.打印数据
        result.print();

        //7.启动
        env.execute();

    }

}
